import { reactive, toRefs } from 'vue'
import useAsync from './useAsync'

const defaultCallBack = (data = {}) => {
  const { total = 0, list = [] } = data?.data || {}
  return {
    total,
    list
  }
}

export default ({
  tableRef,
  tableColumns = [],
  request,
  params = {},
  init = true,
  page = 1,
  limit = 20,
  callback = defaultCallBack
}) => {
  const state = reactive({
    params: {
      ...params,
      page,
      limit
    },
    searchInfo: {},
    list: [],
    columns: tableColumns,
    pagination: {
      page,
      limit,
      total: 0,
      currentChange: (page, limit) => currentChange(page, limit),
      sizeChange: (limit) => sizeChange(limit)
    }
  })

  /** 请求 useAsync */
  const onSuccess = (res) => {
    const result = callback ? callback(res) : res
    const { list, total } = result
    state.list = list
    state.pagination.total = total
  }
  const onError = () => {
    state.list = []
    state.pagination.total = 0
  }
  const { loading, doResult } = useAsync({
    request,
    init: false,
    onSuccess,
    onError
  })

  const searchHandle = (searchInfo = {}) => {
    state.pagination.page = searchInfo.page || page
    state.pagination.limit = searchInfo.limit || limit
    state.searchInfo = searchInfo
    _request(state.searchInfo)
  }

  // page切换
  const currentChange = (page) => {
    state.pagination.page = page
    state.searchInfo.page = page
    _request(state.searchInfo)
  }
  // size
  const sizeChange = (limit) => {
    state.pagination.limit = limit
    state.searchInfo.limit = limit
    state.pagination.page = 1
    state.searchInfo.page = 1
    _request(state.searchInfo)
  }

  const _request = (params = {}) => {
    doResult({ ...state.params, ...params })
  }

  init && _request()

  return {
    tableRef,
    loading,
    ...toRefs(state),
    doResult: searchHandle
  }
}
